﻿namespace AppLab.Data.Models
{
    using System;
    using System.ComponentModel.DataAnnotations;
    using System.Data;
    using System.Data.Objects.DataClasses;
    using System.IO;
    using System.Linq;
    using System.Web.Security;
    using AppLab.Data.Resources;
    using AppLab.Core;

    public sealed partial class SubmitData
    {
        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 0, Name = "BrandLabel", ResourceType = typeof(SubmitDataResources))]
        public int Brand { get; set; }

        [Key]
        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 1, Name = "MobileTypeLabel", ResourceType = typeof(SubmitDataResources))]
        public int Mobile { get; set; }

        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 2, Name = "SubmitTypeLabel", ResourceType = typeof(SubmitDataResources))]
        public int SubmitType { get; set; }

        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [RegularExpression(@".*?\d{1,5}.\d{1,5}.\d{1,5}.\d{1,5}.*", ErrorMessageResourceName = "ValidationErrorInvalidePackageNameFormat", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 3, Name = "PackageNameLabel", Description = "PackageNameDescription", ResourceType = typeof(SubmitDataResources))]
        public string PackageName { get; set; }
        [Display(AutoGenerateField = false)]
        public byte[] PackageContent { get; set; }

        [Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 4, Name = "MediaClientVersionLabel", ResourceType = typeof(SubmitDataResources))]
        public string MediaClientVersion { get; set; }

        //[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [RegularExpression(@".*?\d{1,5}.\d{1,5}.\d{1,5}.\d{1,5}.*", ErrorMessageResourceName = "ValidationErrorInvalidePackageNameFormat", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 5, Name = "UpGradePackageNameLabel", Description = "PackageNameDescription", ResourceType = typeof(SubmitDataResources))]
        public string UpGradePackageName { get; set; }
        [Display(AutoGenerateField = false)]
        public byte[] UpGradePackageContent { get; set; }

        //[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 6, Name = "ReleaseNameLabel", Description = "PackageNameDescription", ResourceType = typeof(SubmitDataResources))]
        public string ReleaseName { get; set; }

        [Display(AutoGenerateField = false)]
        public byte[] ReleaseContent { get; set; }

        //[Required(ErrorMessageResourceName = "ValidationErrorRequiredField", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        [Display(Order = 7, Name = "InsideCompatiableTestReportLabel", Description = "PackageNameDescription", ResourceType = typeof(SubmitDataResources))]
        public string InsideCompatiableTestReportName { get; set; }
        [Display(AutoGenerateField = false)]
        public byte[] InsideCompatiableTestReportContent { get; set; }

        [Display(Order = 8, Name = "AnythingElseLabel", Description = "PackageNameDescription", ResourceType = typeof(SubmitDataResources))]
        public string AnythingElseName { get; set; }
        [Display(AutoGenerateField = false)]
        public byte[] AnythingElseContent { get; set; }

        [Display(AutoGenerateField = false)]
        public string SubmitBy { get; set; }

        [Display(Order = 9, Name = "SubmitCommentLabel", ResourceType = typeof(SubmitDataResources))]
        [StringLength(255, MinimumLength = 0, ErrorMessageResourceName = "ValidationErrorSubmitCommentLength", ErrorMessageResourceType = typeof(ValidationErrorResources))]
        public string SubmitComment { get; set; }

        [Display(AutoGenerateField = false)]
        public string BrandNameStr { get; set; }
        [Display(AutoGenerateField = false)]
        public string MobileTypeStr { get; set; }
        [Display(AutoGenerateField = false)]
        public string SubmitDisplayName { get; set; }

        public Guid ToDataBase()
        {
            try
            {
                Guid FlowGuid = System.Guid.NewGuid();
                if (this.ReleaseContent == null)
                {
                    this.ReleaseName = "";
                }
                if (this.InsideCompatiableTestReportContent == null)
                {
                    this.InsideCompatiableTestReportName = "";
                }
                if (this.AnythingElseContent == null)
                {
                    this.AnythingElseName = "";
                }

                using (var dc = PMSEntities.Create())
                {
                    var e = new tysx_Submit()
                    {
                        SubmitBy = this.SubmitBy,
                        SubmitTime = System.DateTime.Now,
                        SubmitComment = this.SubmitComment,
                        RowGuid = FlowGuid,
                        ReleaseNotesName = this.ReleaseName,
                        ReleaseNotes = this.ReleaseContent,
                        InsideCompatiableTestReportName = this.InsideCompatiableTestReportName,
                        InsideCompatiableTestReport = this.InsideCompatiableTestReportContent,
                        AnythingElseName = this.AnythingElseName,
                        AnythingElse = this.AnythingElseContent,
                        SubmitTypeID = this.SubmitType,
                    };
                    dc.tysx_Submit.AddObject(e);
                    dc.SaveChanges();

                    e.tysx_MediaClient = new tysx_MediaClient()
                    {
                        TerminalID = this.Mobile,
                        MediaClientName = this.PackageName,
                        MediaClientPackage = this.PackageContent,
                        MediaClientVersion = this.MediaClientVersion,
                        RowGuid = e.RowGuid,
                    };
                    dc.tysx_MediaClient.AddObject(e.tysx_MediaClient);
                    dc.SaveChanges();

                    if (!(string.IsNullOrEmpty(this.UpGradePackageName.Replace(" ", "")) || this.UpGradePackageContent == null))
                    {
                        e.tysx_UpgradeMediaClient = new tysx_UpgradeMediaClient()
                        {
                            TerminalID = this.Mobile,
                            UpgradeMediaClientName = this.UpGradePackageName,
                            UpgradeMediaClientPackage = this.UpGradePackageContent,
                            UpgradeMediaClientVersion = this.MediaClientVersion,
                            RowGuid = e.RowGuid,
                        };
                        dc.tysx_UpgradeMediaClient.AddObject(e.tysx_UpgradeMediaClient);
                        dc.SaveChanges();
                    }

                    var flow = new tysx_AppFlow()
                    {
                        SubmitID = e.SubmitID,
                        FlowID = FlowGuid,
                        StateID = 1,
                    };
                    dc.tysx_AppFlow.AddObject(flow);
                    dc.SaveChanges();

                    var da = dc.MoblieAdaptationInfoes.First(p => p.AdaptationTypeID == 2 && p.MobileID == this.Mobile);
                    if (da != null && da.AdaptationStatusID < 4)
                    {
                        da.AdaptationStatusID = 4;
                        dc.SaveChanges();
                    }
                }

                return FlowGuid;
            }
            catch (Exception ex)
            {
                Log.WriteError(this.PackageName + ": Submiting is failed....");
                Log.WriteError(ex.Message);
                Log.WriteError(ex.StackTrace);
                return Guid.Empty;
            }
        }

        public EntityObject ToDatabaseFormat()
        {
            if (string.IsNullOrEmpty(this.UpGradePackageName.Replace(" ", "")) || this.UpGradePackageContent == null)
            {
                return new tysx_Submit()
               {
                   SubmitBy = this.SubmitBy,
                   SubmitTime = System.DateTime.Now,
                   SubmitComment = this.SubmitComment,
                   RowGuid = System.Guid.NewGuid(),
                   ReleaseNotesName = this.ReleaseName,
                   ReleaseNotes = this.ReleaseContent,
                   InsideCompatiableTestReportName = this.InsideCompatiableTestReportName,
                   InsideCompatiableTestReport = this.InsideCompatiableTestReportContent,
                   AnythingElseName = this.AnythingElseName,
                   AnythingElse = this.AnythingElseContent,
                   SubmitTypeID = this.SubmitType,

                   tysx_MediaClient = new tysx_MediaClient()
                   {
                       TerminalID = this.Mobile,
                       MediaClientName = this.PackageName,
                       MediaClientPackage = this.PackageContent,
                       //MediaClientVersion = this.PackageName.Split('-')[0].Substring(5),
                       MediaClientVersion = this.MediaClientVersion,
                       RowGuid = System.Guid.NewGuid(),
                   },
               };
            }
            else
            {
                return new tysx_Submit()
                {
                    SubmitBy = this.SubmitBy,
                    SubmitTime = System.DateTime.Now,
                    SubmitComment = this.SubmitComment,
                    RowGuid = System.Guid.NewGuid(),
                    ReleaseNotesName = this.ReleaseName,
                    ReleaseNotes = this.ReleaseContent,
                    InsideCompatiableTestReportName = this.InsideCompatiableTestReportName,
                    InsideCompatiableTestReport = this.InsideCompatiableTestReportContent,
                    AnythingElseName = this.AnythingElseName,
                    AnythingElse = this.AnythingElseContent,
                    SubmitTypeID = this.SubmitType,

                    tysx_MediaClient = new tysx_MediaClient()
                    {
                        TerminalID = this.Mobile,
                        MediaClientName = this.PackageName,
                        MediaClientPackage = this.PackageContent,
                        //MediaClientVersion = this.PackageName.Split('-')[0].Substring(5),
                        MediaClientVersion = this.MediaClientVersion,
                        RowGuid = System.Guid.NewGuid(),
                    },

                    tysx_UpgradeMediaClient = new tysx_UpgradeMediaClient()
                    {
                        TerminalID = this.Mobile,
                        UpgradeMediaClientName = this.UpGradePackageName,
                        UpgradeMediaClientPackage = this.UpGradePackageContent,
                        //UpgradeMediaClientVersion = this.UpGradePackageName.Split('-')[0].Substring(5),
                        UpgradeMediaClientVersion = this.MediaClientVersion,
                        RowGuid = System.Guid.NewGuid(),
                    },
                };
            }
        }

        #region 发送提交Email

        public void SendEmail()
        {
            //提交后，Email提示审核者、抄送提交者本身
            string toList = "";
            string cCList = "";
            using (var dc = PMSEntities.Create())
            {
                //不能引用AppLab.Web 和 UserRegistrationService，直接写实
                string[] aliasList = Roles.GetUsersInRole("Review");
                foreach (string alias in aliasList)
                {
                    aspnet_Membership am = dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == alias);
                    if (am != null)
                    {
                        toList += am.Email + ";";
                    }
                }
                cCList = dc.aspnet_Membership.FirstOrDefault(p => p.aspnet_Users.UserName == this.SubmitBy).Email;
                this.BrandNameStr = dc.MobileBrands.FirstOrDefault(p => p.BrandID == this.Brand).BrandName;
                this.MobileTypeStr = dc.MobileBasicInfoes.FirstOrDefault(p => p.MobileID == this.Mobile).MobileType;
            }
            string subject = " 新的适配正在等待审核！";
            string bodyStr = System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Resources\SubmitPackaget.htm"));
            bodyStr = string.Format(bodyStr, this.BrandNameStr, this.MobileTypeStr, this.MediaClientVersion, this.SubmitDisplayName,
                DateTime.Now.ToString("yyyy-MM-dd HH:mm"));
            MailUtility.SendMail(toList, cCList, subject, bodyStr);
        }

        #endregion

        //private System.Guid GetMemberId(string alias)
        //{
        //    using (var dc = PMSXEntities.Create())
        //    {
        //        var source = from t in dc.aspnet_Users
        //                     where t.UserName == alias
        //                     select t.UserId;
        //        try
        //        {
        //            return source.First();
        //        }
        //        catch
        //        {
        //            return System.Guid.Empty;
        //        }
        //    }
        //}

    }

}